<template>
    <el-row :gutter="20">
        <el-col :span="7">
            <el-card shadow="hover">
                <div class="card-header">
                    <p class="card-header-title">时间线</p>
                    <p class="card-header-desc">预约病人及时间分布</p>
                </div>
                <el-timeline>
                    <el-timeline-item v-for="(activity, index) in activities" :key="index" :color=getRandomRGBColor()>
                        <div class="timeline-item">
                            <div>
                                <p>{{ activity.userName }}</p>
                                <br />
                                <p class="timeline-desc">预约ID {{ activity.reservationId }}</p>
                            </div>
                            <div class="timeline-time">{{ activity.reserveTime }}
                                <br />
                                <br />
                                <el-button type="success" size="small" round
                                    @click="reservationDetail(Number(activity.reservationId))">填写诊断结果</el-button>
                            </div>
                        </div>
                    </el-timeline-item>
                </el-timeline>
            </el-card>
        </el-col>
        <el-col :span="10">
            <el-card shadow="hover">
                <TableDetail :data="viewData"></TableDetail>
                <br />
                <el-button class="editButton" type="primary" size="small" :icon="Edit" @click="handleEdit()">
                    编辑
                </el-button>
            </el-card>
        </el-col>
    </el-row>
    <el-dialog v-model="visible" width="700px" destroy-on-close :close-on-click-modal="false">
        <TableEdit :form-data="rowData" :options="options" :edit="true" :update="updateDiagnostic" />
    </el-dialog>
</template>

<script lang="ts">
export default {
    name: 'doctor'
}
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { Edit, Plus } from '@element-plus/icons-vue';
import TableDetail from '../../components/table-detail.vue';
import { FormOption } from '../../types/form-option';
import { ElMessage } from 'element-plus';
import axios from '../../utils/request.ts';

const doctor_id = Number(localStorage.getItem('doctors_id'))

const viewData = ref({
    row: {},
    list: []
});

viewData.value.row = {
    diagnosticId: 1,
    username: 'Jone',
    trouble: '抑郁',
    solution: 'wueeeeeeee',
    drugTerms: ['hdajks', 'hnsda', 'shdkja'],
}

interface DrugOption {
    value: string,
    label: string,
}

const drugOpts = ref([
    {
        value: 'Option1',
        label: 'Option1',
    },
    {
        value: 'Option2',
        label: 'Option2',
    },
    {
        value: 'Option3',
        label: 'Option3',
    }
])
const visible = ref(false);
const rowData = ref({});
let options = reactive<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'input', label: '诊断结果', prop: 'solution', required: true },
        { type: 'select', label: 'select', prop: 'drug', required: true, opts: drugOpts, mutable: true },
    ]
})

const reservationDetail = async (id: Number) => {
    try {
        const res = await axios.get('/diagnostic/getByReservationId?reservationId=' + id);
        const { message, data } = res.data;
        if (message === 'success') {
            viewData.value.row.diagnosticId = data.diagnostic.id;
            viewData.value.row.username = data.username;
            viewData.value.row.trouble = data.diagnostic.trouble;
            viewData.value.row.solution = data.diagnostic.solution;
            viewData.value.row.drugTerms = data.drugTerms;
            return;
        } else {
            ElMessage.error("查询失败")
        }
    } catch (error) {
        console.error('Error in fetching data:', error);
    }
}

const updateDiagnostic = async (row: any) => {
    try {
        const res = await axios.post('/diagnostic/doctorAddDiagnostic', {
            diagnosticId: viewData.value.row.diagnosticId,
            doctorId: doctor_id,
            solution: row.solution,
            drugTerms: row.drug,
        });
        const { message, data } = res.data;
        if (message === 'success') {
            return;
        } else {
            ElMessage.error("查询失败")
        }
    } catch (error) {
        console.error('Error in fetching data:', error);
    }
}

const handleEdit = () => {
    visible.value = true
}

viewData.value.list = [
    {
        prop: 'username',
        label: '患者名字',
    },
    {
        prop: 'trouble',
        label: '症状描述',
    },
    {
        prop: 'solution',
        label: '诊断结果和用药建议',
    },
    {
        prop: 'drugTerms',
        label: '药物列表',
    },
]
// username reservationId reserveTime
const activities = reactive([
    {
        userName: '收藏商品',
        reservationId: 'xxx收藏了你的商品，就是不买',
        reserveTime: '30分钟前',
    },
    {
        userName: '用户评价',
        reservationId: 'xxx给了某某商品一个差评，吐血啊',
        reserveTime: '55分钟前',
    },
    {
        userName: '订单提交',
        reservationId: 'xxx提交了订单，快去收钱吧',
        reserveTime: '1小时前',
    },
    {
        userName: '退款申请',
        reservationId: 'xxx申请了仅退款，又要亏钱了',
        reserveTime: '15小时前',
    },
    {
        username: '商品上架',
        reservationId: '运营专员瞒着你上架了一辆飞机',
        reserveTime: '1天前',
    },
]);

function getRandomRGBColor(): string {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    return `rgb(${r}, ${g}, ${b})`;
}

onMounted(() => {
    listReservation();
    listDrug();
})

const listReservation = async () => {
    try {
        const res = await axios.post('/reservation/doctorListReservation', {
            doctorId: doctor_id,
        });
        activities.length = 0;
        const { message, data } = res.data;
        if (message === 'success') {
            for (let i = 0; i < data.length; i++) {
                activities.push({
                    userName: data[i].userName,
                    reservationId: data[i].reservationId,
                    reserveTime: data[i].reserveTime
                })
            }
            console.log('All data fetched successfully');
            return;
        } else {
            ElMessage.error("查询失败")
        }
    } catch (error) {
        console.error('Error in fetching data:', error);
    }
}

const listDrug = async () => {
    try {
        const res = await axios.get('/drug/list');
        const { message, data } = res.data;
        if (message === 'success') {
            drugOpts.value.length = 0
            for (let i = 0; i < data.length; i++) {
                drugOpts.value.push({
                    value: data[i].id,
                    label: data[i].name,
                })
            }

            console.log('All data fetched successfully');
            return;
        } else {
            ElMessage.error("查询失败")
        }
    } catch (error) {
        console.error('Error in fetching data:', error);
    }
}

</script>

<style scoped>
.card-header {
    padding-left: 10px;
    margin-bottom: 20px;
}

.card-header-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 5px;
}

.card-header-desc {
    font-size: 14px;
    color: #999;
}

.timeline-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    color: #000;
}

.timeline-time,
.timeline-desc {
    font-size: 12px;
    color: #787878;
}
</style>